package org.whereiswally.net.picturerepository;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.whereiswally.WallyConstants;

public abstract class PictureRepository implements Serializable {

    private URI uri;

    private static final Logger logger = Logger
	    .getLogger(PictureRepository.class);

    public PictureRepository(URI uri) {
	super();
	this.uri = uri;
    }

    // public abstract List<URL> getPicturesOfAlbum(URL albumURL);

    // public abstract List<URL> getAlbumsOfUser(URL albumURL);

    /**
     * @return the uri
     */
    public URI getUri() {
	return uri;
    }

    public abstract List<URI> getAllPicturesOfRepository();

    public static File downloadPicture(URI uri) {
	logger.debug("Downloadin picture of: " + uri);
	try {
	    URLConnection uc = uri.toURL().openConnection();
	    uc.connect();
	    InputStream is = uc.getInputStream();

	    File tmp = new File(WallyConstants.TMP_DIR
		    + System.currentTimeMillis() + ".jpg");

	    IOUtils.copy(is, new FileOutputStream(tmp));

	    return tmp;
	} catch (Exception e) {
	    logger.error(e);
	    return null;
	}
    }

    public static List<File> downloadPictures(List<URI> uri) {
	List<File> pictures = new ArrayList<File>();
	for (URI uri2 : uri) {
	    pictures.add(downloadPicture(uri2));
	}
	return pictures;
    }

}
